package com.egg.gateway.config;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.egg.common.core.enums.ResponseCode;
import com.egg.common.core.exception.CustomException;
import com.egg.common.util.JsonUtil;
import com.egg.gateway.utils.WebFluxUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * 覆盖默认的异常处理
 */
@Slf4j
@Configuration
@EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class})
public class ExceptionHandlerConfig implements ErrorWebExceptionHandler {


    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        if (exchange.getResponse().isCommitted()) {
            return Mono.error(ex);
        }
        Integer code;
        String msg;
        if (ex.getCause() instanceof CustomException) {
            CustomException cust = JsonUtil.objToObj(ex.getCause(), CustomException.class);
            code = cust.getCode();
            msg = cust.getMessage();
        } else if (ex instanceof BlockException) {
            code = ResponseCode.FALLBACK_ERROR.getCode();
            msg = ResponseCode.FALLBACK_ERROR.getMessage();
        } else {
            code = ResponseCode.SYSTEM_ERROR.getCode();
            msg = ResponseCode.SYSTEM_ERROR.getMessage();
        }
        log.error("[网关异常处理]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), ex.getMessage());
        return WebFluxUtils.webFluxResponseWriter(response, msg, code);
    }


}